using ProtoBuf;
using System.IO;
using System.Collections.Generic;
using System;

namespace FutureCore
{
    public static class ProtobufHelper
    {
        #region Serialize Deserialize
        public static byte[] Serialize<T>(T obj)
        {
            byte[] result = null;
            if (obj != null)
            {
                using (var stream = new MemoryStream())
                {
                    Serializer.Serialize(stream, obj);
                    result = stream.ToArray();
                }
            }
            return result;
        }

        public static object Deserialize(Type protoType, byte[] bytes, int index, int count)
        {
            object result = null;
            using (MemoryStream stream = new MemoryStream(bytes, index, count))
            {
                result = Serializer.NonGeneric.Deserialize(protoType, stream);
            }
            return result;
        }

        public static object Deserialize(Type protoType, byte[] bytes)
        {
            object result = null;
            using (MemoryStream stream = new MemoryStream(bytes))
            {
                result = Serializer.NonGeneric.Deserialize(protoType, stream);
            }
            return result;
        }

        public static T Deserialize<T>(byte[] bytes, int index, int count)
        {
            T result = default(T);
            if (bytes != null)
            {
                using (MemoryStream stream = new MemoryStream(bytes, index, count))
                {
                    result = Serializer.Deserialize<T>(stream);
                }
            }
            return result;
        }

        public static T Deserialize<T>(byte[] bytes)
        {
            T result = default(T);
            if (bytes != null)
            {
                using (MemoryStream stream = new MemoryStream(bytes))
                {
                    result = Serializer.Deserialize<T>(stream);
                }
            }
            return result;
        }
        #endregion

        #region Assign
        public static void Assign<T>(List<T> rawList, List<T> tarList)
        {
            rawList.Clear();
            rawList.AddRange(tarList);
        }

        public static void Assign<T>(List<T> rawList, T tarData)
        {
            rawList.Clear();
            rawList.Add(tarData);
        }
        #endregion
    }
}